﻿// ----------------------------------------------------------------------
// <author name="Moses Kehengu"/>
// <copyright file="SMSReminder.cs" company="Futures Group International">
//     Copyright statement. All right reserved
// </copyright>
//
// ------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using GenericTools;
using System.Data.Common;
using GenericTools.Models;
using System.Drawing;
using DataModels.Enumerations;
using DataModels.Common;

namespace ReportingManagement
{
    public partial class MainWindow
    {
        private const int AUTO_REMINDER_WEEKLY_DAYS_GAP = 6;
        private const int AUTO_REMINDER_MONTHLY_DAYS_GAP = 25;

        private bool tabPageSMSReminderLoaded = false;
        //private List<List<string>> facilitiesPhoneNumbers = new List<List<string>>();
        private Dictionary<string, List<string>> facilitiesExcludePhoneNumbers = new Dictionary<string, List<string>>();
        //private List<string> facilitiesCodes = new List<string>();
        private DataTable appropriateFacilities = null;
        //private DataTable districts = null;
        //private DataTable regions = null;

        private void dgvFacilitiesWithoutReports_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.authenticatedUser.Level == AccessLevel.NATION) return;
            if (this.authenticatedUser.Level == AccessLevel.REGION) return;

            if (e.RowIndex > -1)
            {
                DataGridViewRow row = dgvFacilitiesWithoutReports.Rows[e.RowIndex];

                string facility = row.Cells[0].Value.ToString();
                string facilityName = row.Cells[1].Value.ToString();
                int period = int.Parse(cboPeriod.SelectedValue.ToString());
                int year = int.Parse(cboYear.SelectedValue.ToString());

                List<string> previousList = null;
                if (row.Tag != null) previousList = (List<string>)row.Tag;
                else
                {
                    Cursor.Current = Cursors.WaitCursor;
                    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    DataTable users = Utilities.GetRegisteredReportingUsers(facility);
                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = "Ready";

                    List<string> usersCellNumber = new List<string>();
                    foreach (DataRow r in users.Rows)
                    {
                        string number = r["Cell number"].ToString();
                        bool send = bool.Parse(r["Send SMS"].ToString());
                        if (send) usersCellNumber.Add(number);
                    }
                    // Store facility registered user (only selected to receive SMS) with it.
                    row.Tag = usersCellNumber;
                    previousList = usersCellNumber;
                }

                Cursor.Current = Cursors.WaitCursor;
                FacilityReportInfo facilityReportInfo = new FacilityReportInfo(facility, facilityName, period, year, previousList);
                Cursor.Current = Cursors.Default;

                DialogResult response = facilityReportInfo.ShowDialog(this);
                if (response == System.Windows.Forms.DialogResult.OK)
                {
                    //this.facilitiesPhoneNumbers[e.RowIndex] = facilityReportInfo.SelectedPhoneNumbers;
                    facilitiesExcludePhoneNumbers[facility] = facilityReportInfo.ExcludedPhoneNumbers;
                }
            }
        }

        private void tabPageSMSReminder_Enter(object sender, EventArgs e)
        {
            if (!tabPageSMSReminderLoaded)
            {
                try
                {
                    switch (this.authenticatedUser.Level)
                    {
                        case AccessLevel.DISTRICT:
                            rdoDisplayByDistrict.Enabled = false;
                            rdoDisplayByRegion.Enabled = false;
                            break;

                        case AccessLevel.REGION:
                            rdoDisplayByRegion.Enabled = false;
                            break;
                    }

                    dgvFacilitiesWithoutReports.SuspendLayout();
                    PopulateReportList();
                    PopulateMonthList();
                    PopulateYearList();

                    DateTime previousMonthDate = DateTime.Now.AddMonths(-1);
                    cboPeriod.SelectedValue = previousMonthDate.Month;
                    cboYear.SelectedValue = previousMonthDate.Year;

                    PopulateDisplayByDistrictList();
                    PopulateDisplayByRegionList();
                    dgvFacilitiesWithoutReports.ResumeLayout();
                    PopulateFacilityList();
                    //rdoFilterByFacilities.Checked = true;
                    //rdoAtleastOneMissingReport.Checked = true;

                    string setting = Utilities.GetSetting(AutoReminderSettings.AUTO_REMINDER_LAST_SEND_DATE);
                    DateTime reminderLastSendDate;
                    if (!DateTime.TryParse(setting, out reminderLastSendDate))
                    {
                        reminderLastSendDate = DateTime.Now.AddMonths(-1);
                    }

                    string sRemindingDate = string.Format("{0:ddd, dd MMM yyyy hh:mm tt}", reminderLastSendDate);
                    lblLastSendReportNote.Text = string.Format("Note: Last auto-reminder was sent on {0}", sRemindingDate);
                    TimeSpan timeGap = DateTime.Now - reminderLastSendDate;
                    lblLastSendReportNote.ForeColor = timeGap.TotalDays > AUTO_REMINDER_WEEKLY_DAYS_GAP ? Color.Green : Color.Brown; 

                    tabPageSMSReminderLoaded = true;
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                }
            }
        }

        private void cboReports_SelectedIndexChanged(object sender, EventArgs e)
        {
            //PopulateFacilityList();
            btnShowRemindingFacilities.Enabled = true;
        }

        private void cboPeriod_SelectedIndexChanged(object sender, EventArgs e)
        {
            //PopulateFacilityList();
            btnShowRemindingFacilities.Enabled = true;
        }

        private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            //PopulateFacilityList();
            btnShowRemindingFacilities.Enabled = true;
        }

        private void PopulateReportList()
        {
            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            DataTable dataTable = Utilities.GetAllExpectedReportViews();
            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Ready";
            cboReports.Items.Clear();
            foreach (DataRow row in dataTable.Rows)
            {
                ListItem item = new ListItem();
                item.Text = row["ReportName"].ToString();
                item.Value = row["RepID"];
                cboReports.Items.Add(item);
            }
            try
            {
                cboReports.SelectedIndex = 0;
            }
            catch { }
        }

        private void PopulateMonthList()
        {
            DataTable dataTable = new DataTable();
            DataColumn column = new DataColumn("Period", Type.GetType("System.Int32"));
            dataTable.Columns.Add(column);
            column = new DataColumn("Month", Type.GetType("System.String"));
            dataTable.Columns.Add(column);

            DataRow row = null;
            for (int i = 1; i < 13; i++)
            {
                row = dataTable.NewRow();
                row["Period"] = i;
                row["Month"] = Utilities.GetMonthText(i);
                dataTable.Rows.Add(row);
            }

            cboPeriod.DataSource = dataTable;
            cboPeriod.DisplayMember = "Month";
            cboPeriod.ValueMember = "Period";
        }

        private void PopulateYearList()
        {
            DataTable dataTable = new DataTable();
            DataColumn column = new DataColumn("Year", Type.GetType("System.Int32"));
            dataTable.Columns.Add(column);

            int currentYear = DateTime.Now.Year;
            DataRow row = dataTable.NewRow();
            row["Year"] = currentYear;
            dataTable.Rows.Add(row);

            row = dataTable.NewRow();
            row["Year"] = currentYear - 1;
            dataTable.Rows.Add(row);

            cboYear.DataSource = dataTable;
            cboYear.DisplayMember = "Year";
            cboYear.ValueMember = "Year";
        }

        private void PopulateDisplayByDistrictList()
        {
            DataTable dataTable = null;
            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            switch (this.authenticatedUser.Level)
            {
                case AccessLevel.DISTRICT:
                    int districtID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                    dataTable = Utilities.GetDistrict(districtID);
                    break;

                case AccessLevel.REGION:
                    int regionID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                    dataTable = Utilities.GetDistrictsByRegion(regionID, this.authenticatedUser.SupportingPartnerId);
                    break;

                case AccessLevel.NATION:
                    dataTable = Utilities.GetAllDistricts(this.authenticatedUser.SupportingPartnerId);
                    break;

                default:
                    dataTable = Utilities.GetAllDistricts();
                    break;
            }
            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Ready";

            cboDisplayByDistrict.DataSource = null;
            cboDisplayByDistrict.ValueMember = "DistrictNo";
            cboDisplayByDistrict.DisplayMember = "District";
            cboDisplayByDistrict.DataSource = dataTable;
        }

        private void PopulateDisplayByRegionList()
        {
            DataTable dataTable = null;
            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            switch (this.authenticatedUser.Level)
            {
                case AccessLevel.REGION:
                    int regionID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                    dataTable = Utilities.GetRegion(regionID);
                    break;

                case AccessLevel.NATION:
                    dataTable = Utilities.GetAllRegions(this.authenticatedUser.SupportingPartnerId);
                    break;

                default:
                    dataTable = Utilities.GetAllRegions();
                    break;
            }
            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Ready";

            cboDisplayByRegion.DataSource = null;
            cboDisplayByRegion.ValueMember = "RegionID";
            cboDisplayByRegion.DisplayMember = "RegionName";
            cboDisplayByRegion.DataSource = dataTable;
        }

        private void PopulateFacilityList()
        {
            try
            {
                ListItem item = (ListItem)cboReports.SelectedItem;
                int reportID = int.Parse(item.Value.ToString());
                int period = int.Parse(cboPeriod.SelectedValue.ToString());
                int year = int.Parse(cboYear.SelectedValue.ToString());
                bool missingAtLeastOneReport = rdoAtleastOneMissingReport.Checked;

                int displayByDistrictId = default(int);
                int displayByRegionId = default(int);

                Cursor.Current = Cursors.WaitCursor;
                toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                DataTable dataTable = null;
                switch (this.authenticatedUser.Level)
                {
                    case AccessLevel.DISTRICT:
                        int districtID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                        if (missingAtLeastOneReport)
                        {
                            dataTable = Utilities.GetDistrictFacilitiesWithoutReport(districtID, period, year);
                        }
                        else
                        {
                            dataTable = Utilities.GetDistrictFacilitiesWithoutReport(districtID, reportID, period, year);
                        }
                        this.appropriateFacilities = Utilities.GetAllDistrictFacilitiesStatus(districtID);
                        rdoFilterByRegions.Enabled = false;
                        //this.appropriateFacilities = dataTable;
                        //this.districts = Utilities.GetDistrict(districtID);
                        //this.regions = Utilities.GetDistrictRegion(districtID);
                        break;

                    case AccessLevel.REGION:
                        int regionID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                        if (missingAtLeastOneReport)
                        {
                            if (rdoDisplayByDistrict.Checked)
                            {
                                displayByDistrictId = Int32.Parse(cboDisplayByDistrict.SelectedValue.ToString());
                                dataTable = Utilities.GetRegionFacilitiesWithoutReport(regionID, period, year, 
                                    this.authenticatedUser.SupportingPartnerId, displayByDistrictId, default(bool));
                            }
                            else
                            {
                                dataTable = Utilities.GetRegionFacilitiesWithoutReport(regionID, period,
                                    year, this.authenticatedUser.SupportingPartnerId, default(bool));
                            }
                        }
                        else
                        {
                            if (rdoDisplayByDistrict.Checked)
                            {
                                displayByDistrictId = Int32.Parse(cboDisplayByDistrict.SelectedValue.ToString());
                                dataTable = Utilities.GetRegionFacilitiesWithoutReport(regionID, reportID, period, 
                                    year, this.authenticatedUser.SupportingPartnerId, displayByDistrictId);
                            }
                            else
                            {
                                dataTable = Utilities.GetRegionFacilitiesWithoutReport(regionID,
                                   reportID, period, year, this.authenticatedUser.SupportingPartnerId);
                            }
                        }
                        //this.appropriateFacilities = dataTable;
                        this.appropriateFacilities = Utilities.GetAllRegionFacilitiesStatus(regionID, 
                            this.authenticatedUser.SupportingPartnerId);
                        //gboReminder.Enabled = false;
                        gboReminder.Enabled = true;
                        //btnStatusDetails.Visible = false;
                        //this.districts = Utilities.GetDistrictsByRegion(regionID);
                        //this.regions = Utilities.GetRegion(regionID);
                        break;

                    case AccessLevel.NATION:
                        if (missingAtLeastOneReport)
                        {
                            if (rdoDisplayByDistrict.Checked)
                            {
                                displayByDistrictId = Int32.Parse(cboDisplayByDistrict.SelectedValue.ToString());
                                dataTable = Utilities.GetFacilitiesWithoutReport(period, year,
                                    this.authenticatedUser.SupportingPartnerId, displayByDistrictId, default(bool));
                            }
                            else if (rdoDisplayByRegion.Checked)
                            {
                                displayByRegionId = Int32.Parse(cboDisplayByRegion.SelectedValue.ToString());
                                dataTable = Utilities.GetFacilitiesWithoutReport(period, year,
                                    this.authenticatedUser.SupportingPartnerId, default(bool), displayByRegionId);
                            }
                            else
                            {
                                dataTable = Utilities.GetFacilitiesWithoutReport(period, year,
                                    this.authenticatedUser.SupportingPartnerId, default(bool));
                            }
                        }
                        else
                        {
                            if (rdoDisplayByDistrict.Checked)
                            {
                                displayByDistrictId = Int32.Parse(cboDisplayByDistrict.SelectedValue.ToString());
                                dataTable = Utilities.GetFacilitiesWithoutReport(reportID, period, year, 
                                    this.authenticatedUser.SupportingPartnerId, displayByDistrictId);
                            }
                            else if (rdoDisplayByRegion.Checked)
                            {
                                displayByRegionId = Int32.Parse(cboDisplayByRegion.SelectedValue.ToString());
                                dataTable = Utilities.GetFacilitiesWithoutReport(reportID, period, year, 
                                    this.authenticatedUser.SupportingPartnerId, displayByRegionId, default(bool));
                            }
                            else
                            {
                                dataTable = Utilities.GetFacilitiesWithoutReport(reportID,
                                   period, year, this.authenticatedUser.SupportingPartnerId);
                            }
                        }
                        this.appropriateFacilities = Utilities.GetAllFacilitiesStatus(this.authenticatedUser.SupportingPartnerId);
                        //this.appropriateFacilities = dataTable;
                        //this.districts = Utilities.GetAllDistricts();
                        //this.regions = Utilities.GetAllRegions();
                        //gboReminder.Enabled = false;
                        gboReminder.Enabled = true;
                        //btnStatusDetails.Visible = false;
                        break;

                    case AccessLevel.ADMINISTRATOR:
                        if (missingAtLeastOneReport)
                        {
                            if (rdoDisplayByDistrict.Checked)
                            {
                                displayByDistrictId = Int32.Parse(cboDisplayByDistrict.SelectedValue.ToString());
                                dataTable = Utilities.GetFacilitiesWithoutReport(period, year, displayByDistrictId, null);
                            }
                            else if (rdoDisplayByRegion.Checked)
                            {
                                displayByRegionId = Int32.Parse(cboDisplayByRegion.SelectedValue.ToString());
                                dataTable = Utilities.GetFacilitiesWithoutReport(period, year, null, displayByRegionId);
                            }
                            else
                            {
                                dataTable = Utilities.GetFacilitiesWithoutReport(period, year);
                            }
                        }
                        else
                        {
                            if (rdoDisplayByDistrict.Checked)
                            {
                                displayByDistrictId = Int32.Parse(cboDisplayByDistrict.SelectedValue.ToString());
                                dataTable = Utilities.GetFacilitiesWithoutReport(reportID, period, year, displayByDistrictId, null);
                            }
                            else if (rdoDisplayByRegion.Checked)
                            {
                                displayByRegionId = Int32.Parse(cboDisplayByRegion.SelectedValue.ToString());
                                dataTable = Utilities.GetFacilitiesWithoutReport(reportID, period, year, null, displayByRegionId);
                            }
                            else
                            {
                                dataTable = Utilities.GetFacilitiesWithoutReport(reportID, period, year);
                            }
                        }
                        this.appropriateFacilities = Utilities.GetAllFacilitiesStatus();
                        //this.appropriateFacilities = dataTable;
                        break;
                }
                Cursor.Current = Cursors.Default;
                toolStripStatusLabel.Text = "Ready";
                dgvFacilitiesWithoutReports.DataSource = dataTable;
                dgvFacilitiesWithoutReports.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvFacilitiesWithoutReports.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

                //this.facilitiesPhoneNumbers.Clear();
                //Cursor.Current = Cursors.WaitCursor;
                //toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                //foreach (DataRow row in dataTable.Rows)
                //{
                //    string facilityCode = row["Facility Code"].ToString();
                //    DataTable users = Utilities.GetRegisteredReportingUsers(facilityCode);

                //    List<string> usersCellNumber = new List<string>();
                //    foreach (DataRow r in users.Rows)
                //    {
                //        string number = r["Cell number"].ToString();
                //        bool send = bool.Parse(r["Send SMS"].ToString());
                //        if (send) usersCellNumber.Add(number);
                //    }
                //    this.facilitiesPhoneNumbers.Add(usersCellNumber);
                //    this.facilitiesCodes.Add(facilityCode);
                //}
                //Cursor.Current = Cursors.Default;
                //toolStripStatusLabel.Text = "Ready";

                if (dataTable.Rows.Count == 0)
                {
                    lblReminderStatus.ForeColor = System.Drawing.Color.Blue;
                    lblReminderStatus.Text = String.Format(
                        "There is no facility which have not submitted its {0} {1} report",
                        Utilities.GetMonthText(period), year);
                }
                else
                {
                    lblReminderStatus.ForeColor = System.Drawing.Color.Red;
                    if (dataTable.Rows.Count == 1)
                    {
                        lblReminderStatus.Text = String.Format(
                            "There is {0} facility which have not submitted its {1} {2} report",
                            dataTable.Rows.Count, Utilities.GetMonthText(period), year);
                    }
                    else
                    {
                        lblReminderStatus.Text = String.Format(
                            "There are {0} facilities which have not submitted their {1} {2} reports",
                            dataTable.Rows.Count, Utilities.GetMonthText(period), year);
                    }
                }

                if (rdoAtleastOneMissingReport.Checked)
                {
                    string messageTemplate = "Tafadhali kamilisha kutuma taarifa za PMTCT za mwezi: {0} {1}";
                    txtMessage.Text = String.Format(messageTemplate, Utilities.GetMonthText(period), year);
                }
                else
                {
                    string messageTemplate = "Tafadhali tuma taarifa za {0} za mwezi: {1} {2}";
                    string reportName = cboReports.Text;
                    txtMessage.Text = String.Format(messageTemplate, reportName, Utilities.GetMonthText(period), year);
                }

                if (rdoFilterByFacilities.Checked) rdoFilterByFacilities_CheckedChanged(null, null);
                if (rdoFilterByDistricts.Checked) rdoFilterByDistricts_CheckedChanged(null, null);
                if (rdoFilterByRegions.Checked) rdoFilterByRegions_CheckedChanged(null, null);
                btnStatusDetails.Enabled = (dgvFacilitiesWithoutReports.Rows.Count > 0);
            }
            catch { }
        }

        private bool SendSMSReminder()
        {
            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Generating List of Facilities to send, please wait...";
            btnSendReminder.Enabled = false;
            Application.DoEvents();

            string message = this.txtMessage.Text;
            if (String.IsNullOrEmpty(message)) return false;

            int year = -1;
            int period = -1;
            int reportID = -1;
            try
            {
                year = int.Parse(cboYear.SelectedValue.ToString());
                period = int.Parse(cboPeriod.SelectedValue.ToString());
                ListItem item = (ListItem)cboReports.SelectedItem;
                reportID = int.Parse(item.Value.ToString());
            }
            catch
            {
                return false;
            }

            List<string> facilitiesCodes1 = new List<string>();
            if (rdoFilterByFacilities.Checked)
            {
                List<ListItem> selectedFacilities = listBoxSelection.SelectedList;
                foreach (ListItem i in selectedFacilities) facilitiesCodes1.Add(i.Value.ToString());
            }

            if (rdoFilterByDistricts.Checked)
            {
                List<ListItem> selectedDistricts = listBoxSelection.SelectedList;
                foreach (ListItem i in selectedDistricts)
                {
                    string district = i.Text;
                    foreach (DataGridViewRow r in dgvFacilitiesWithoutReports.Rows)
                    {
                        string facilityCode = r.Cells[0].Value.ToString();
                        foreach (DataRow row in this.appropriateFacilities.Rows)
                        {
                            string code = row[0].ToString();
                            if (facilityCode == code)
                            {
                                string dist = row["District Name"].ToString();
                                if (district == dist) facilitiesCodes1.Add(code);
                                break;
                            }
                        }
                    }
                }
            }

            if (rdoFilterByRegions.Checked)
            {
                List<ListItem> selectedRegions = listBoxSelection.SelectedList;
                foreach (ListItem i in selectedRegions)
                {
                    string region = i.Text;
                    foreach (DataGridViewRow r in dgvFacilitiesWithoutReports.Rows)
                    {
                        string facilityCode = r.Cells[0].Value.ToString();
                        foreach (DataRow row in this.appropriateFacilities.Rows)
                        {
                            string code = row[0].ToString();
                            if (facilityCode == code)
                            {
                                string reg = row["Region Name"].ToString();
                                if (region == reg) facilitiesCodes1.Add(code);
                                break;
                            }
                        }
                    }
                }
            }

            //foreach (DataGridViewRow row in dgvFacilitiesWithoutReports.Rows)
            //{
            //    string code = row.Cells["Facility Code"].Value.ToString();
            //    facilitiesCodes1.Add(code);
            //}

            List<string> excludedNumbers = new List<string>();
            foreach (string facility in this.facilitiesExcludePhoneNumbers.Keys)
            {
                List<string> numbers = this.facilitiesExcludePhoneNumbers[facility];
                excludedNumbers.AddRange(numbers);
            }

            toolStripStatusLabel.Text = "Preparing to send Reminder"; Application.DoEvents();
            bool repeat = cboRepeatSendingReminder.Checked;
            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            //Utilities.SendSMSReminderWithPhoneNumbers(reportID, year, period, message, this.facilitiesPhoneNumbers, this.facilitiesCodes, repeat);
            Utilities.SendSMSReminder(reportID, year, period, message, excludedNumbers, facilitiesCodes1, repeat);
            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Ready";
            btnSendReminder.Enabled = true;
            return true;
        }

        private void btnSendReminder_Click(object sender, EventArgs e)
        {
            if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
            {
                string message = @"The application is running in offline mode. " +
                    "You can not perform any activities that require server " +
                    "connection while you are offline. " +
                    "\n\nYou are current operation will not be processed!";
                MessageBox.Show(this, message, AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            if (listBoxSelection.SelectedList.Count < 1)
            {
                MessageBox.Show(this, "Please select at least one facility, district or region for sending reminder",
                    AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            if (String.IsNullOrEmpty(txtMessage.Text))
            {
                MessageBox.Show(this, "Message contents can not be empty", "SMS Reminder",
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                txtMessage.Focus();
                return;
            }

            //int recipientCount = 0;
            //foreach (List<string> x in this.facilitiesPhoneNumbers) recipientCount += x.Count;

            DialogResult response = MessageBox.Show(this,
                "Are you sure you want to send SMS reminder to registered users at facilities which have not sent their reports?",
                "SMS Reminder Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (response == System.Windows.Forms.DialogResult.Yes)
            {
                bool okToContinue = false;
                try
                {
                    string setting = Utilities.GetSetting(AutoReminderSettings.AUTO_REMINDER_LAST_SEND_DATE);
                    DateTime reminderLastSendDate;
                    if (DateTime.TryParse(setting, out reminderLastSendDate))
                    {
                        TimeSpan timeGap = DateTime.Now - reminderLastSendDate;
                        if (timeGap.TotalDays < AUTO_REMINDER_WEEKLY_DAYS_GAP)
                        {
                            int days = (int)timeGap.TotalDays;
                            response = MessageBox.Show(this, 
                                string.Format("These facilities were reminded automatically just {0} days ago!\n\nAre you sure you want to repeat the same thing now?", 
                                    days), 
                                AppConfiguration.ApplicationName, MessageBoxButtons.YesNo, 
                                MessageBoxIcon.Question);
                            if (response == System.Windows.Forms.DialogResult.No) return;
                        }
                    }                    

                    okToContinue = SendSMSReminder();
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                }

                if (okToContinue) 
                    MessageBox.Show(this, "You have successfully sent SMS reminder", "SMS Reminder",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);

                else
                    MessageBox.Show(this, "Sending SMS reminder did not complete", "SMS Reminder",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void rdoFilterByFacilities_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoFilterByFacilities.Checked)
            {
                listBoxSelection.AvailableTitle = "Available Facilities";
                listBoxSelection.SelectedTitle = "Selected Facilities";

                List<ListItem> items = new List<ListItem>();
                foreach (DataGridViewRow r in dgvFacilitiesWithoutReports.Rows)
                {
                    ListItem i = new ListItem();
                    i.Value = r.Cells[0].Value;
                    i.Text = r.Cells[1].Value.ToString();
                    items.Add(i);
                }
                listBoxSelection.DataSource = items;
            }
        }

        private void rdoFilterByDistricts_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoFilterByDistricts.Checked)
            {
                listBoxSelection.AvailableTitle = "Available Districts";
                listBoxSelection.SelectedTitle = "Selected Districts";

                List<ListItem> items = new List<ListItem>();
                List<string> districts = new List<string>();
                foreach (DataGridViewRow r in dgvFacilitiesWithoutReports.Rows)
                {
                    string facilityCode = r.Cells[0].Value.ToString();
                    foreach (DataRow row in this.appropriateFacilities.Rows)
                    {
                        string code = row[0].ToString();
                        if (facilityCode == code)
                        {
                            string district = row["District Name"].ToString();
                            if (!districts.Contains(district)) districts.Add(district);
                            break;
                        }
                    }
                }
                foreach (string d in districts)
                {
                    ListItem i = new ListItem();
                    i.Text = d;
                    i.Value = d;
                    items.Add(i);
                }
                listBoxSelection.DataSource = items;
            }
        }

        private void rdoFilterByRegions_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoFilterByRegions.Checked)
            {
                listBoxSelection.AvailableTitle = "Available Regions";
                listBoxSelection.SelectedTitle = "Selected Regions";

                List<ListItem> items = new List<ListItem>();
                List<string> regions = new List<string>();
                foreach (DataGridViewRow r in dgvFacilitiesWithoutReports.Rows)
                {
                    string facilityCode = r.Cells[0].Value.ToString();
                    foreach (DataRow row in this.appropriateFacilities.Rows)
                    {
                        string code = row[0].ToString();
                        if (facilityCode == code)
                        {
                            string region = row["Region Name"].ToString();
                            if (!regions.Contains(region)) regions.Add(region);
                            break;
                        }
                    }
                }
                foreach (string r in regions)
                {
                    ListItem i = new ListItem();
                    i.Text = r;
                    i.Value = r;
                    items.Add(i);
                }
                listBoxSelection.DataSource = items;
            }
        }

        private void btnStatusDetails_Click(object sender, EventArgs e)
        {
            //if (this.authenticatedUser.Level == AccessLevel.NATION) return;
            //if (this.authenticatedUser.Level == AccessLevel.REGION) return;

            if (dgvFacilitiesWithoutReports.SelectedRows.Count > 0)
            {
                DataGridViewRow row = dgvFacilitiesWithoutReports.SelectedRows[0];

                string facility = row.Cells[0].Value.ToString();
                string facilityName = row.Cells[1].Value.ToString();
                int period = int.Parse(cboPeriod.SelectedValue.ToString());
                int year = int.Parse(cboYear.SelectedValue.ToString());

                List<string> previousList = null;
                if (row.Tag != null) previousList = (List<string>)row.Tag;
                else
                {
                    Cursor.Current = Cursors.WaitCursor;
                    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    DataTable users = Utilities.GetRegisteredReportingUsers(facility);
                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = "Ready";

                    List<string> usersCellNumber = new List<string>();
                    foreach (DataRow r in users.Rows)
                    {
                        string number = r["Cell number"].ToString();
                        bool send = bool.Parse(r["Send SMS"].ToString());
                        if (send) usersCellNumber.Add(number);
                    }
                    // Store facility registered user (only selected to receive SMS) with it.
                    row.Tag = usersCellNumber;
                    previousList = usersCellNumber;
                }

                Cursor.Current = Cursors.WaitCursor;
                FacilityReportInfo facilityReportInfo = new FacilityReportInfo(facility, facilityName, period, year, previousList);
                Cursor.Current = Cursors.Default;

                DialogResult response = facilityReportInfo.ShowDialog(this);
                if (response == System.Windows.Forms.DialogResult.OK)
                {
                    //this.facilitiesPhoneNumbers[e.RowIndex] = facilityReportInfo.SelectedPhoneNumbers;
                    facilitiesExcludePhoneNumbers[facility] = facilityReportInfo.ExcludedPhoneNumbers;
                }
            }
            else
            {
                MessageBox.Show(this, "Please select a facility to view its details associated with reminder",
                    AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnShowRemindingFacilities_Click(object sender, EventArgs e)
        {
            PopulateFacilityList();
            btnShowRemindingFacilities.Enabled = false;
        }

        private void rdoAtleastOneMissingReport_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoAtleastOneMissingReport.Checked)
            {
                cboReports.Enabled = false;
                int period = DateTime.Now.Month;
                int year = DateTime.Now.Year;

                int.TryParse(cboPeriod.SelectedValue.ToString(), out period);
                int.TryParse(cboYear.SelectedValue.ToString(), out year);

                string messageTemplate = "Tafadhali kamilisha kutuma taarifa za PMTCT za mwezi: {0} {1}";
                txtMessage.Text = String.Format(messageTemplate, Utilities.GetMonthText(period), year);
            }
            else
            {
                cboReports.Enabled = true;
            }
            btnShowRemindingFacilities.Enabled = true;
        }

        private void rdoMissingReport_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoMissingReport.Checked)
            {
                cboReports.Enabled = true;
            }
            else
            {
                cboReports.Enabled = false;
                int period = DateTime.Now.Month;
                int year = DateTime.Now.Year;

                int.TryParse(cboPeriod.SelectedValue.ToString(), out period);
                int.TryParse(cboYear.SelectedValue.ToString(), out year);

                string messageTemplate = "Tafadhali kamilisha kutuma taarifa za PMTCT za mwezi: {0} {1}";
                txtMessage.Text = String.Format(messageTemplate, Utilities.GetMonthText(period), year);
            }
            btnShowRemindingFacilities.Enabled = true;
        }

        private void rdoDisplayAll_CheckedChanged(object sender, EventArgs e)
        {
            btnShowRemindingFacilities.Enabled = true;
        }

        private void rdoDisplayByDistrict_CheckedChanged(object sender, EventArgs e)
        {
            btnShowRemindingFacilities.Enabled = true;
            cboDisplayByDistrict.Enabled = rdoDisplayByDistrict.Checked;
        }

        private void cboDisplayByDistrict_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnShowRemindingFacilities.Enabled = true;
        }

        private void rdoDisplayByRegion_CheckedChanged(object sender, EventArgs e)
        {
            btnShowRemindingFacilities.Enabled = true;
            cboDisplayByRegion.Enabled = rdoDisplayByRegion.Checked;
        }

        private void cboDisplayByRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnShowRemindingFacilities.Enabled = true;
        }    
    }
}
